import React, { useEffect, useRef, useCallback } from 'react';
import { Spin } from 'antd';

interface InfiniteScrollProps {
  loadMore: () => void;
  hasMore: boolean;
  isLoading: boolean;
  children: React.ReactNode;
  currentPage: number;
  totalItems: number;
}

const InfiniteScroll: React.FC<InfiniteScrollProps> = ({ 
  loadMore, 
  hasMore, 
  isLoading, 
  children, 
  currentPage,
  totalItems
}) => {
  const observer = useRef<IntersectionObserver | null>(null);
  const lastElementRef = useCallback(
    (node: HTMLDivElement | null) => {
      if (isLoading) return;
      if (observer.current) observer.current.disconnect();
      observer.current = new IntersectionObserver((entries) => {
        if (entries[0].isIntersecting && hasMore) {
          loadMore();
        }
      });
      if (node) observer.current.observe(node);
    },
    [isLoading, hasMore, loadMore]
  );

  return (
    <>
      {children}
      <div ref={lastElementRef} style={{ height: 1 }} />
      {isLoading && (
        <div className="text-center py-4">
          <Spin />
          <p>正在加载第 {currentPage} 页 (共 {totalItems} 项)</p>
        </div>
      )}
      {!isLoading && !hasMore && (
        <div className="text-center py-4">
          没有更多数据了 (共 {totalItems} 项)
        </div>
      )}
    </>
  );
};

export default InfiniteScroll; 